<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionClass :class-id="listQuery.class_id" @setSearchClassId="searchClassId" />
      <SearchOptionUser @setSearchUserId="searchUserId" />
      <el-select v-model="listQuery.type" placeholder="用户类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in istypeOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-select v-model="listQuery.is_manage" placeholder="是否班级管理" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in ismanageOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="用户ID" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userInfo.number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级" prop="class_id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.classInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否班级管理" align="center">
        <template slot-scope="{row}">
          <span>{{ ismanageOption[row.is_manage] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{row}">
          <span>{{ istypeOption[row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户" prop="user_id">
          <el-input v-model="temp.name" readonly />
        </el-form-item>
        <el-form-item v-model="temp.class_id" label="班级" prop="class_id" class="filter-item">
          <SearchOptionClass :class-id="temp.class_id" @setSearchClassId="updateClassId" />
        </el-form-item>
        <el-form-item label="管理" prop="is_manage">
          <el-select v-model="temp.is_manage" class="filter-item">
            <el-option v-for="(value,key) in quarterOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { classUserPage, classUserUpdate, classUserDelete, classUserCreate } from '@/api/class'
import waves from '@/directive/waves'
import { isInteger } from '@/utils/validate'
import { notifySuccess, formatJson, listQueryFilter, my_confirm } from '@/utils/tool'
import Pagination from '@/components/Pagination'
import SearchOptionClass from '@/components/SearchOption/class'
import SearchOptionUser from '@/components/SearchOption/user'
export default {
  name: 'ClassUserPage',
  components: { Pagination, SearchOptionClass, SearchOptionUser },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: undefined,
        quarter: undefined,
        semester: undefined,
        class_id: undefined,
        user_id: undefined,
        is_manage: undefined
      },
      istypeOption: { 1: '老师', 2: '学生', 3: '导师' },
      ismanageOption: { 0: '否', 1: '是' },
      quarterOption: { 0: '否', 1: '是' },
      temp: {
        id: undefined,
        type: '',
        quarter: '',
        semester: '',
        class_id: '',
        user_id: '',
        is_manage: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        class_id: [{ required: true, message: '班级必选', trigger: 'change' }],
        type: [{ required: true, message: '类型必选', trigger: 'change' }],
        user_id: [{ required: true, message: '学生ID必填且是数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }],
        is_manage: [{ required: true, message: '管理必选', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.listQuery.class_id = this.$route.query.id
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      classUserPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        quarter: '',
        semester: '',
        class_id: '',
        user_id: '',
        is_manage: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          classUserCreate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.type = row.type
      this.temp.class_id = row.class_id
      this.temp.user_id = row.user_id
      this.temp.is_manage = row.is_manage
      this.temp.name = row.userInfo.name
      this.temp.number = row.userInfo.number
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {}
          tempData.id = this.temp.id
          tempData.class_id = this.temp.class_id
          tempData.is_manage = this.temp.is_manage
          classUserUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        classUserDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['班级ID', '类型', '用户ID', '管理']
        const filterVal = ['class_id', 'type', 'user_id', 'is_manage']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '班级里的用户配置'
        })
        this.downloadLoading = false
      })
    },
    searchClassId: function(data) {
      this.listQuery.class_id = data.classId
    },
    searchUserId: function(data) {
      this.listQuery.user_id = data.userId
    },
    updateClassId: function(data) {
      this.temp.class_id = data.classId
    }
  }
}
</script>
